﻿// -----------------------------------------------------------------------
// <copyright file="Invert.cs" company="Microsoft">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace ImagePackage.Core.PixelOperations.Parallel
{
    using System;
    using System.Threading.Tasks;
    using Model;
    using Utilities;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public class Invert : PixelOperations.Invert
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Invert"/> class.
        /// </summary>
        /// <param name="inputImage">The input image.</param>
        public Invert(Image inputImage)
            : base(inputImage)
        {
        }

        /// <summary>
        /// Applies the operation.
        /// Requires the input image
        /// </summary>
        /// <returns>
        /// Image object
        /// </returns>
        public override Image Apply()
        {
            Logger.Debug("Start applying Parallel Invert operation");
            try
            {
                Image buffer = new Image(this.InputImage.Width, this.InputImage.Height);
                Parallel.For(
                    0,
                    this.InputImage.Width * this.InputImage.Height,
                   index =>
                   {
                       int i = index / this.InputImage.Height;

                       int j = index % this.InputImage.Height;

                       Pixel oldPixel = this.InputImage[i, j];

                       Pixel newPixel = ~oldPixel;

                       buffer[i, j] = newPixel;
                   });

                return buffer;
            }
            catch (Exception ex)
            {
                Logger.LogException("Something wrong happened in Parallel Invert Operation", ex);
                throw;
            }
            finally
            {
                Logger.Debug("Finished applying Parallel Invert operation");
            }
        }
    }
}
